package com.foryou.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.foryou.wechat.common.Constants;
import com.foryou.wechat.model.vo.UserIndexVo;
import com.foryou.wechat.model.vo.UserInfoVo;
import com.foryou.wechat.service.UserService;
import com.foryou.wechat.utils.HttpClientUtil;
import com.foryou.wechat.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lee.
 */
@RequestMapping("/v/wx/")
@RestController
public class LoginController {

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public Response login(@RequestParam("code") String code,
                          @RequestParam("avatarUrl") String avatarUrl,
                          @RequestParam("nickname") String nickname,
                          @RequestParam("gender") String gender) {

        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", appId);
        param.put("secret", appSecret);
        param.put("js_code", code);
        param.put("grant_type", Constants.WX_LOGIN_GRANT_TYPE);

        // 发送请求
        String wxResult = HttpClientUtil.doGet(Constants.WX_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        // 获取参数返回的
        String sessionKey = jsonObject.get("session_key").toString();
        String open_id = jsonObject.get("openid").toString();
        UserInfoVo response = (UserInfoVo) userService.userLogin(open_id, nickname, avatarUrl, gender, sessionKey).getData();
        JSONObject result = new JSONObject();
        result.put("userInfo", response);
        result.put("token", sessionKey);
        return Response.success(result);
    }

    @GetMapping("/logout")
    public Response logout() {
        return Response.success();
    }
}
